VideoMode(800,600)

Camera_SetPosition(-2,4,10)
Camera_SetRotation(20,-20)

rate = 7

keydownaction = {
	p = function() Sound_Tak() end
}

keyactions = {
	a = function(dt) Camera_Move(0,-rate*dt,0) end,
	space = function(dt) Camera_Move(0,rate*dt,0) end,
	s = function(dt) Camera_MoveRelative(0, -rate*dt) end,
	f = function(dt) Camera_MoveRelative(0, rate*dt) end,
	e = function(dt) Camera_MoveRelative(rate*dt, 0) end,
	d = function(dt) Camera_MoveRelative(-rate*dt, 0) end,
}
keysdown = {}

function keydown(key)
	keysdown[key] = 1
	if keydownaction[key] ~= nil then
		keydownaction[key]()
	end
end

function keyup(key) 
	keysdown[key] = nil
end

function mousedown(btn) print("mousedown", btn) end
function mouseup  (btn) print("mouseup", btn) end
function mousemotion(x,y) 
	Camera_Rotate(x/10,-y/10)
end

function tick(dt, now)
	for k,v in pairs(keysdown) do
		if keyactions[k] ~= nil then
			keyactions[k](dt)
		end
	end
	updatespider(dt, now)
end

function randf() return math.random(0,1e6-1) / 1e6 end

for i = 0, 500 do
	x = math.random(-50,49)
	y = math.random(-50,49)
	z = math.random(-50,49)
	Box(x,y,z,x+1,y+1,z+1)
end

Box(0,0,0,1,1,1)
Box(0,0,0,-1,-1,-1)
Box(0,0,1,1,1,3)
Box(1,0,1,2,3,2)

Box(-1,0,1,-4,-1,4)
spider_id = Spider(-2.5,0.5,2.5)
Spider_MoveLeg(spider_id, 0, .75, -.4, .5);
Spider_MoveLeg(spider_id, 1, .0, -.4, .5);
Spider_MoveLeg(spider_id, 2,-.75, -.4, .5);
Spider_MoveLeg(spider_id, 3, .75, -.4, -.5);
Spider_MoveLeg(spider_id, 4, .0, -.4, -.5);
Spider_MoveLeg(spider_id, 5,-.75, -.4, -.5);

for i = 0,5 do
	Spider_SetLegMode(spider_id, i, true)
end

spiderlegpos = {}
function updatespider(dt, now)
	Spider_Move(spider_id, .2*dt, 0, 0)
	x, y, z = Spider_GetPos(spider_id)
	for i = 0,5 do
		x1, y1, z1 = Spider_GetLegPos(spider_id, i)
		x2, y2, z2 = x-x1, y-y1, z-z1
		if math.sqrt(x2*x2+y2*y2+z2*z2) >= .95 and spiderlegpos[i] == nil and x2 > 0 then
			if i == 0 or i == 1 or i ==2 then
				spiderlegpos[i] = 
					function (n) return -math.cos(2*(n-now)-.4899)*.866, 
										math.sin(2*(n-now)-.4899)*.866, .5, 2*(n-now) end
			end
			if i == 3 or i == 4 or i == 5 then
				spiderlegpos[i] = 
					function (n) return -math.cos(2*(n-now)-.4899)*.866, 
										math.sin(2*(n-now)-.4899)*.866, -.5, 2*(n-now) end
			end
				
			Spider_SetLegMode(spider_id, i, false)
		end

		if spiderlegpos[i] ~= nil then
			x1, y1, z1, t = spiderlegpos[i](now)
			Spider_MoveLeg(spider_id, i, x1, y1, z1)
			if t > math.pi+2*.4899 then
				Spider_SetLegMode(spider_id, i, true)
				spiderlegpos[i] = nil
			end
		end
	end
end

